/* eslint-disable no-mixed-spaces-and-tabs */
/*****
 * CONFIGURATION
 */
// Active ajax page loader
$.ajaxLoad = true;

// required when $.ajaxLoad = true
$.defaultPage = 'main';
$.subPagesDirectory = '/admin/views/';
$.page404 = 'pages/404.html';
$.mainContent = $('#ui-view');

// Main navigation
$.navigation = $('nav > ul.nav');

$.panelIconOpened = 'icon-arrow-up';
$.panelIconClosed = 'icon-arrow-down';

// Default colours
$.brandPrimary = '#20a8d8';
$.brandSuccess = '#79c447';
$.brandInfo = '#67c2ef';
$.brandWarning = '#fabb3d';
$.brandDanger = '#ff5454';

$.grayDark = '#384042';
$.gray = '#9faecb';
$.grayLight = '#c0cadd';
$.grayLighter = '#e1e6ef';
$.grayLightest = '#f9f9fa';

'use strict';


/*****
 * ASYNC LOAD
 * Load JS files and CSS files asynchronously in ajax mode
 */
function loadJS(jsFiles, pageScript) {
    var i;
    for (i = 0; i < jsFiles.length; i++) {
        var body = document.getElementsByTagName('body')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = false;
        script.src = jsFiles[i];
        body.appendChild(script);
    }

    if (pageScript) {
        var body = document.getElementsByTagName('body')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = false;
        script.src = pageScript;
        body.appendChild(script);
    }

    init();
}

function loadCSS(cssFile, end, callback) {
    var cssArray = {};

    if (!cssArray[cssFile]) {
        cssArray[cssFile] = true;

        if (end == 1) {
            var head = document.getElementsByTagName('head')[0];
            var s = document.createElement('link');
            s.setAttribute('rel', 'stylesheet');
            s.setAttribute('type', 'text/css');
            s.setAttribute('href', cssFile);

            s.onload = callback;
            head.appendChild(s);
        } else {
            var head = document.getElementsByTagName('head')[0];
            var style = document.getElementById('main-style');

            var s = document.createElement('link');
            s.setAttribute('rel', 'stylesheet');
            s.setAttribute('type', 'text/css');
            s.setAttribute('href', cssFile);

            s.onload = callback;
            head.insertBefore(s, style);
        }
    } else if (callback) {
        callback();
    }
}

/****
 * AJAX LOAD
 * Load pages asynchronously in ajax mode
 */

if ($.ajaxLoad) {
    var paceOptions = {
        elements: false,
        restartOnRequestAfter: false
    };

    var url = location.hash.replace(/^#/, '');

    if (url != '') {
        setUpUrl(url);
    } else {
        setUpUrl($.defaultPage);
    }

    $(document).on('click', '.nav a[href!="#"]', function (e) {
        if ($(this).parent().parent().hasClass('nav-tabs') || $(this).parent().parent().hasClass('nav-pills')) {
            e.preventDefault();
        } else if ($(this).attr('target') == '_top') {
            e.preventDefault();
            var target = $(e.currentTarget);
            window.location = (target.attr('href'));
        } else if ($(this).attr('target') == '_blank') {
            e.preventDefault();
            var target = $(e.currentTarget);
            window.open(target.attr('href'));
        } else {
            e.preventDefault();
            var target = $(e.currentTarget);
            setUpUrl(target.attr('href'));
        }
    });

    $(document).on('click', 'a[href="#"]', function (e) {
        e.preventDefault();
    });
}

function setUpUrl(url) {
    $('nav .nav li .nav-link').removeClass('active');
    $('nav .nav li.nav-dropdown').removeClass('open');
    $('nav .nav li:has(a[href="' + url.split('?')[0] + '"])').addClass('open');
    $('nav .nav a[href="' + url.split('?')[0] + '"]').addClass('active');

    loadPage(url);
}

$(function () {
    //$('body').css('overflow','hidden');
    $("#mainNiceScroll").height($(window).height() - 120);//.css({"overflow": "hidden","height":"499px"})
    $("#mainNiceScroll").niceScroll({
        //cursorwidth: "2px"
        cursorcolor: "#ccc",//#CC0071 光标颜色
        disableoutline: true,
        cursoropacitymax: 1, //改变不透明度非常光标处于活动状态（scrollabar“可见”状态），范围从1到0
        touchbehavior: false, //使光标拖动滚动像在台式电脑触摸设备
        cursorwidth: "5px", //像素光标的宽度
        cursorborder: "0", // 游标边框css定义
        cursorborderradius: "5px",//以像素为光标边界半径
        //railpadding:"0,0,0,55",
        //horizrailenabled:false,
        autohidemode: true //是否隐藏滚动条
    });

});

function goheight() {
    var ms = $("#mainNiceScroll").height();
    var ws = $(window).height() - 120;
    var gs
    if (ms < ws) {
        gs = ws;
    } else if (ms > ws) {
        gs = ws
    }
    $("#mainNiceScroll").height(gs);//.css({"overflow": "hidden","height":"499px"})
    $("#mainNiceScroll").getNiceScroll().resize();
}

function loadPage(url) {
    $.ajax({
        type: 'GET',
        url: $.subPagesDirectory + url,
        dataType: 'html',
        cache: false,
        async: false,
        beforeSend: function () {
            $.mainContent.css({opacity: 0});
        },
        complete: function () {
            //alert(data.height())

        },
        success: function () {
            var a = $.mainContent.height()
            var b = $(window).height()
            //var c =$.replace(url,'/')[0])
            //var c = $('#'+url.split('/')[0]).height()
            //alert(c)

            //$('#mainNiceScroll').height(b)
            //$('#ui-view').height(a)
            //$.mainContent.css({"height":(c)+"px"})

            Pace.restart();
            $('html, body').animate({scrollTop: 0}, 0);
            //document.documentElement.style.overflow = "hidden";
            $.mainContent.load($.subPagesDirectory + url, null, function (responseText) {
                goheight()
                $("#mainNiceScroll").getNiceScroll().resize();

                window.location.hash = url;
            }).delay(250).animate({opacity: 1}, 0);
        },
        error: function () {
            window.location.href = ""//$.page404;
        }

    });
}


$(window).resize(function () {          //当浏览器大小变化时
    goheight()
    $("#mainNiceScroll").getNiceScroll().resize();
    //alert($(window).height());          //浏览器时下窗口可视区域高度
    //alert($(document).height());        //浏览器时下窗口文档的高度
    //alert($(document.body).height());   //浏览器时下窗口文档body的高度
    //alert($(document.body).outerHeight(true)); //浏览器时下窗口文档body的总高度 包括border padding margin
});
/****
 * MAIN NAVIGATION
 */

$(document).ready(function ($) {
    // Add class .active to current link - AJAX Mode off
    $.navigation.find('a').each(function () {
        var cUrl = String(window.location).split('?')[0];

        if (cUrl.substr(cUrl.length - 1) == '#') {
            cUrl = cUrl.slice(0, -1);
        }

        if ($($(this))[0].href == cUrl) {
            $(this).addClass('active');

            $(this).parents('ul').add(this).each(function () {
                $(this).parent().addClass('open');
            });
        }
    });

    // Dropdown Menu
    $.navigation.on('click', 'a', function (e) {
        if ($.ajaxLoad) {
            e.preventDefault();
        }

        if ($(this).hasClass('nav-dropdown-toggle')) {
            $(this).parent().toggleClass('open');
            resizeBroadcast();
        }
    });

    function resizeBroadcast() {
        var timesRun = 0;
        var interval = setInterval(function () {
            timesRun += 1;
            if (timesRun === 5) {
                clearInterval(interval);
            }
            window.dispatchEvent(new Event('resize'));
        }, 62.5);
    }

    /* ---------- Main Menu Open/Close, Min/Full ---------- */
    $('.navbar-toggler').click(function () {
        if ($(this).hasClass('sidebar-toggler')) {
            $('body').toggleClass('sidebar-hidden');
            resizeBroadcast();
        }

        if ($(this).hasClass('sidebar-minimizer')) {
            $('body').toggleClass('sidebar-minimized');
            resizeBroadcast();
        }

        if ($(this).hasClass('aside-menu-toggler')) {
            $('body').toggleClass('aside-menu-hidden');
            resizeBroadcast();
        }

        if ($(this).hasClass('mobile-sidebar-toggler')) {
            $('body').toggleClass('sidebar-mobile-show');
            resizeBroadcast();
        }
    });

    $('.sidebar-close').click(function () {
        $('body').toggleClass('sidebar-opened').parent().toggleClass('sidebar-opened');
    });

    /* ---------- Disable moving to top ---------- */
    $('a[href="#"][data-top!=true]').click(function (e) {
        e.preventDefault();
    });
});

/****
 * CARDS ACTIONS
 */

$(document).on('click', '.card-actions a', function (e) {
    e.preventDefault();

    if ($(this).hasClass('btn-close')) {
        $(this).parent().parent().parent().fadeOut();
    } else if ($(this).hasClass('btn-minimize')) {
        var $target = $(this).parent().parent().next('.card-block');
        if (!$(this).hasClass('collapsed')) {
            $('i', $(this)).removeClass($.panelIconOpened).addClass($.panelIconClosed);
        } else {
            $('i', $(this)).removeClass($.panelIconClosed).addClass($.panelIconOpened);
        }
    } else if ($(this).hasClass('btn-setting')) {
        $('#myModal').modal('show');
    }
});

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function init(url) {
    /* ---------- Tooltip ---------- */
    $('[rel="tooltip"],[data-rel="tooltip"]').tooltip({'placement': 'bottom', delay: {show: 400, hide: 200}});

    /* ---------- Popover ---------- */
    $('[rel="popover"],[data-rel="popover"],[data-toggle="popover"]').popover();
}

//$('.get-nicer').css({"height":""+$(document).height()-300+"px;"})
$(window).resize(function () {
    var wh = $(document).height();
    $('#mainNiceScroll').css({"height": "" + wh - 300 + "px;"})

    //alert(wh)
    //$('#mainNiceScroll').addClass()
    //$('#mainNiceScroll').css({"overflow": "auto","height":""+wh-300+"px;"})
});


//验证并提交
//a:formId,b:验证参数
function goFormValidator(a, b) {
    var sController = a;
    var sRules = b;
    if (a == null) return false;
    var sAction = $('#' + sController + 'Action').val();
    //alert(sRules)
    var sForm = $('#' + sController + 'Form');
    var sMethod = sForm.attr('method');
    //sForm.empty();/////////
    sForm.validate({
        //errorClass:'label.error',
        submitHandler: function () {
            goAjaxData(sController, sAction, sMethod, goFormToJson(sForm), function (data) {
                goUrl_Toastr(data);
                //sForm[0].reset();
            });
        },
        rules: sRules,
        errorElement: 'span',
        // 错误提示位置
        errorPlacement: function (error, element) {
            // Add the `help-block` class to the error element
            error.addClass('fa fa-warning');
            if (element.prop('type') === 'checkbox') {
                error.insertAfter(element.parent('label'));
            } else {
                error.insertAfter(element);
            }
        },

        highlight: function (element, errorClass, validClass) {
            $(element).addClass('fa fa-warning').removeClass('form-control-success');
            //$( element ).parents( '.form-group' ).addClass( 'has-danger' ).removeClass( 'has-success' );
        },
        unhighlight: function (element, errorClass, validClass) {
            //$( element ).addClass( 'form-control-success' ).removeClass( 'form-control-danger' );
            $(element).parents('.form-group').addClass('has-success').removeClass('fa fa-warning');
        }
    });
}

/**
 * 改变角色状态
 */
function _chsta(status, id, key) {
    $.ajax({
        url: '/admin/views/' + goUrlAction() + '/chsta',
        data: {status: status, id: id, key: key},
        success: function (res) {
            if (res) {
                $('#' + goUrlAction() + 'Table').bootstrapTable('refresh');
                toastr.success('状态更新成功！')
            } else {
                toastr.error("状态更新失败！");
            }
        }
    })
}

function goActionTitle(a) {
    switch (a) {
        case('list'): {
            return '列表';
        }
            break;
        case('add'): {
            return '添加';
        }
            break;
        case('edit'): {
            return '编辑';
        }
            break;
        case('del'): {
            return '';
        }
            break;
        default:
            return '';
    }
}
function goTitle(a){
    if(a!=null){
        switch (a) {
            case('menu'): {
                return '目录';
            }
                break;
            case('user'): {
                return '用户';
            }
                break;
            case('edit'): {
                return '编辑';
            }
                break;
            case('del'): {
                return '';
            }
                break;
            default:
                return '';
        }
    }
}

// loaded 在模态框加载的同时做一些动作
// show 在show方法后调用
// shown 在模态框完全展示出来做一些动作
// hide hide方法后调用
// hiden 监听模态框隐藏事件做一些动作
function goModel(a) {
    var sA = a;
    var sTitle = goActionTitle(sA);
    var sController = goUrlAction();
    var sAction = $('#' + sController + 'Action');
    var sModal = $('#' + sController + 'Modal');
    var sModalLabel = $('#' + sController + 'ModalLabel');
    var sForm = $('#' + sController + 'Form')
    var sTableId = $('#' + sController + 'Table').bootstrapTable('getSelections');
    sModalLabel.empty();//清楚Model标题
    //alert(sA);
    //sForm.validate({submitHandler:function(form){alert("submitted");form.submit();
    goEmptyValidateError(sForm);//清除验证error提示
    switch (sA) {
        case('add'): {
            sModalLabel.append(sTitle+goTitle(sController));
            sForm[0].reset();
            sModal.modal('show');
            sAction.val(sA);
        }
            break;
        case('edit'): {
            sForm[0].reset();
            if (sTableId.length == 1) {
                sModalLabel.append(sTitle+goTitle(sController));
                sModal.modal('show');
                goAjaxData(sController, sA, 'GET', 'id=' + sTableId[0].Id, function (data) {
                    goJsonToForm(data, sForm);
                    sAction.val(sA);
                });
            }
            else {
                goToastr('warning', '警告', '请选择一条有效数据!');
                return false;
            }
        }
            break;
        case('del'): {
            if (sTableId.length == 1) {
                goBootBox('confirm', '确定要删除吗?', function (result) {
                    if (result) {
                        goAjaxData(sController, sA, 'GET', 'id=' + sTableId[0].Id, function (data) {
                            goUrl_Toastr(data);
                        })
                    }
                });
                //});
            }
            else {
                goToastr('warning', '警告', '请选择一条有效数据!');
                return false;
            }

        }
            break;
        default:
            return false;
            break;
    }
}

function goUrl_Toastr(data) {
    alert(data.errno)
    if (data.errno == 0) {
        if (data.url) {
            goToastr('success', data.title, data.message)
            setTimeout(function () {
                location.href = data.url;//后台指定跳转地址
            }, 1500)
        }
        else {
            goToastr('success', data.title, data.message)
            setTimeout(function () {
                location.reload();//默认跳转当前地址
            }, 1500)
        }
    } else {
        goToastr('error', data.title, data.message)
        setTimeout(function () {
            if (data.url) {
                location.href = data.url;//后台指定跳转地址
            } else {
                goToastr('', '', '')
            }
        }, 1500)
    }
}

function goToastr(s, msg, msgstr) {
    toastr.options = {
        "closeButton": true,//关闭按钮
        "progressBar": true,//进度条
        "positionClass": "toast-bottom-right",//显示位置
        "preventDuplicates": true,//防止重复
    }
    switch (s) {
        case('success'):
            toastr.success(msgstr, msg);
            break;
        case('error'):
            toastr.error(msgstr, msg);
            break;
        case('warning'):
            toastr.warning(msgstr, msg);
            break;
        case('info'):
            toastr.info(msgstr, msg);
            break;
        default:
            toastr.clear();
            break;
    }
}

//确认或提示框
function goBootBox(s, msg, fn) {
    switch (s) {
        case('alert'):
            bootbox.alert({
                message: msg,
                callback: fn
            });
            break;
        case('prompt'):
            bootbox.prompt({
                message: msg,
                callback: fn
            });
            break;
        case('confirm'):
            bootbox.confirm({
                message: msg,
                callback: fn
            });
            break;
    }
}


//将form中的值转换为键值对。
function goFormToJson(frm) {
    var o = {};
    var a = $(frm).serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
//重载DIV后清楚验证错误提示
function goEmptyValidateError(frm){
    var a = $(frm).serializeArray();
    $.each(a, function () {
        $('#'+this.name+'-error').empty();
        $('#'+this.name+'-error').removeClass();

    });
    //u_name-error
}

//a:控制器,b:执行,c:method,d:数据,e:返回
function goAjaxData(a, b, c, d, e) {
    $.ajax({
        url: '/admin/views/' + a + '/' + b,
        type: c,
        data: d,
        success: e,
        error: function () {
            goToastr('error', '错误', '错误原因未知!');
        }
    });
}

//Table提取
function goTable(ids, urls, column) {
    $(ids).bootstrapTable({
        contentType: 'application/json',
        classes: 'table-no-bordered',
        sortStable: true,
        dataType: 'json',
        totalField: 'totalPages',
        dataField: 'data',
        striped: true, // 使表格带有条纹
        pagination: true, // 在表格底部显示分页工具栏
        pageSize: 1, // 如果设置了分页，页面数据条数
        pageNumber: 1, // 如果设置了分页，首页页码
        // pageList: [10, 20, 50, 100, 200, 500],
        idField: 'Id', // 标识哪个字段为id主键
        showToggle: false, // 名片格式
        cardView: false, // 设置为True时显示名片（card）布局
        showColumns: false, // 显示隐藏列
        showRefresh: true, // 显示刷新按钮
        singleSelect: true, // 复选框只能选择一条记录
        search: true, // 是否显示右上角的搜索框
        clickToSelect: true, // 点击行即可选中单选/复选框
        sidePagination: 'server', // 表格分页的位置
        queryParamsType: 'limit', // 参数格式,发送标准的RESTFul类型的参数请求
        toolbar: '#toolbar', // 设置工具栏的Id或者class
        silent: true, // 刷新事件必须设置
        url: urls,//'/admin/views/user/listuser', // 请求后台的URL（*）
        method: 'post', // 请求方式（*）
        paginationLoop: false, // 设置为 true 启用分页条无限循环的功能。
        onlyInfoPagination: false,
        paginationVAlign: 'bottom',
        maintainSelected: false, // 	设置为 true 在点击分页按钮或搜索按钮时，将记住checkbox的选择项
        icons: {
            refresh: 'fa fa-refresh'
        },
        formatLoadingMessage: function () {
            return '请稍等，正在加载中...';
        },
        formatNoMatches: function () { // 没有匹配的结果
            return '无符合条件的记录';
        },
        onLoadError: function (data) {
            $(ids).bootstrapTable('removeAll');
        },
        columns: [column]
    });
    //替换默认刷新按钮Class
    var b = $('button[name="refresh"]');
    b.removeClass('btn btn-default');
    b.addClass('btn btn-primary ');
}

//获取url中的参数
function goUrlAction() {
    var s = window.location.hash;
    var sp = s.split('#');
    var sl = sp.length;
    var t

    if (sp[1].split('/').length > 1) {
        t = sp[1].split('/')[0]
    }
    else {
        t = sp[1]
    }
    //alert(t)
    if (t != null) return t;
    return null;
}


/*
 * jquery 初始化form插件，传入一个json对象，为form赋值
 * version: 1.0.0-2013.06.24
 * @requires jQuery v1.5 or later
 * Copyright (c) 2013
 * note:  1、此方法能赋值一般所有表单，但考虑到checkbox的赋值难度，以及表单中很少用checkbox，这里不对checkbox赋值
 *        2、此插件现在只接收json赋值，不考虑到其他的来源数据
 *        3、对于特殊的textarea，比如CKEditor,kindeditor...，他们的赋值有提供不同的自带方法，这里不做统一，如果项目中有用到，不能正确赋值，请单独赋值
 */

// a:Data,b:目标Form
function goJsonToForm(a, b) {
    //默认参数
    var jsonValue;
    var defaults = {
        jsonValue: a,
        isDebug: false   //是否需要调试，这个用于开发阶段，发布阶段请将设置为false，默认为false,true将会把name value打印出来
    };
    if (a != null && b != null) {
        //设置参数
        var setting = $.extend({}, defaults);
        var form = b;
        jsonValue = setting.jsonValue;
        //如果传入的json字符串，将转为json对象
        if ($.type(setting.jsonValue) === "string") {
            jsonValue = $.parseJSON(jsonValue);
        }

        //如果传入的json对象为空，则不做任何操作
        if (!$.isEmptyObject(jsonValue)) {
            var debugInfo = "";
            $.each(jsonValue, function (key, value) {
                //是否开启调试，开启将会把name value打印出来
                if (setting.isDebug) {
                    alert("name:" + key + "; value:" + value);
                    debugInfo += "name:" + key + "; value:" + value + " || ";
                }
                var formField = form.find("[name='" + key + "']");
                if ($.type(formField[0]) === "undefined") {
                    if (setting.isDebug) {
                        alert("can not find name:[" + key + "] in form!!!");    //没找到指定name的表单
                    }
                } else {
                    var fieldTagName = formField[0].tagName.toLowerCase();
                    if (fieldTagName == "input") {
                        if (formField.attr("type") == "radio") {
                            $("input:radio[name='" + key + "'][value='" + value + "']").attr("checked", "checked");
                        } else {
                            formField.val(value);
                        }
                    } else if (fieldTagName == "select") {
                        //do something special
                        formField.val(value);
                    } else if (fieldTagName == "textarea") {
                        //do something special
                        formField.val(value);
                    } else {
                        formField.val(value);
                    }
                }
            })
            if (setting.isDebug) {
                alert(debugInfo);
            }
        }
        return form;    //返回对象，提供链式操作
    }
}

